package cn.xiaopengstack.config;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseCookie;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.MultiValueMap;
import reactor.core.publisher.Flux;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CachedClientHttpResponse implements ClientHttpResponse {
    private final ClientHttpResponse originalResponse;
    private byte[] bodyBytes;

    public CachedClientHttpResponse(ClientHttpResponse originalResponse) throws IOException {
        this.originalResponse = originalResponse;
        // 预先读取并缓存响应体
        this.bodyBytes = originalResponse.getBody().readAllBytes();
    }

    @Override
    public HttpStatus getStatusCode() throws IOException {
        HttpStatusCode statusCode = originalResponse.getStatusCode();
        return HttpStatus.valueOf(statusCode.value());
    }


    @Override
    public String getStatusText() throws IOException {
        return originalResponse.getStatusText();
    }

    @Override
    public void close() {
        originalResponse.close();
    }

    @Override
    public InputStream getBody() throws IOException {
        // 返回一个新的ByteArrayInputStream，包含缓存的响应体内容
        return new ByteArrayInputStream(bodyBytes);
    }

    @Override
    public HttpHeaders getHeaders() {
        return originalResponse.getHeaders();
    }

    // 获取缓存的响应体字节数组
    public byte[] getBodyBytes() {
        return bodyBytes;
    }
}
